package com.blogManager.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.blogManager.entity.PageResult;
import com.blogManager.mapper.TbBlogMapper;
import com.blogManager.pojo.TbBlog;
import com.blogManager.pojo.TbBlogExample;
import com.blogManager.pojo.TbBlogExample.Criteria;
import com.blogManager.service.BlogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class BlogServiceImpl implements BlogService {

	@Autowired
	private TbBlogMapper blogMapper;

	@Autowired
	private RedisTemplate redisTemplate;

	public PageResult getBlogList(int page, int rows) {
		
		PageHelper.startPage(page, rows);
		List<TbBlog> blogList = blogMapper.selectByExample(null);
		PageInfo<TbBlog> pageInfo = new PageInfo<TbBlog>(blogList);
		// 封装页面包装对象
		PageResult pageResult = new PageResult();
		pageResult.setCurrentPage(pageInfo.getPageNum());
		pageResult.setTotal((int) pageInfo.getTotal());
		pageResult.setList(blogList);
		pageResult.setPageNum(pageInfo.getPages());
		return pageResult;
	}

	public PageResult search(int page, int rows, TbBlog blog) {
		PageHelper.startPage(page, rows);
		TbBlogExample example = new TbBlogExample();
		Criteria criteria = example.createCriteria();
		if (blog != null) {
			if (blog.getTitle() != null && blog.getTitle().length() > 0) {
				criteria.andTitleLike("%" + blog.getTitle() + "%");
			}
		}
		List<TbBlog> blogList = blogMapper.selectByExample(example);
		PageInfo<TbBlog> pageInfo = new PageInfo<TbBlog>(blogList);
		// 封装页面包装对象
		PageResult pageResult = new PageResult();
		pageResult.setCurrentPage(pageInfo.getPageNum());
		pageResult.setTotal((int) pageInfo.getTotal());
		pageResult.setList(blogList);
		pageResult.setPageNum(pageInfo.getPages());
		// 将结果存入缓存
		return pageResult;
	}

	public void delete(int[] ids) {
		redisTemplate.delete("blogList");
		for (int id : ids) {
			blogMapper.deleteByPrimaryKey(id);
		}
	}

	public void add(TbBlog blog) {
		redisTemplate.delete("blogList");// 删除缓存
		blog.setCreatedate(new Date());
		blog.setUpdatedate(new Date());
		blogMapper.insert(blog);
	}

	public void update(TbBlog blog) {
		redisTemplate.delete("blogList");// 删除缓存
		blogMapper.updateByPrimaryKey(blog);
	}

	public TbBlog findBlogById(int blogId) {
		return blogMapper.selectByPrimaryKey(blogId);
	}

}
